package com.hzeport.bgs22emduty.config.interptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.owasp.esapi.ESAPI;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

@Slf4j
@Component
public class ParameterInterceptor implements HandlerInterceptor {




    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ServletAttributes.setRequest(request);
        response.setHeader("Set-Cookie","cookiename=cookievalue; path=/; Domain=domainvalue; Max-age=seconds; HttpOnly");
        String author=request.getHeader("origin");
        log.info(author+"author1");
        if(StringUtils.isEmpty(author)){
            author=request.getHeader("Referer");
            log.info(author+"author2");
        }
        String jsonString= JSONObject.toJSONString(author);
        jsonString= ESAPI.encoder().encodeForHTML(jsonString);
        jsonString=ESAPI.encoder().decodeForHTML(jsonString);
        author=JSONObject.parseObject(jsonString, String.class);
//        if (author!=null && Pattern.matches("[0-9A-Za-z]+", author)) {
            response.setHeader("Access-Control-Allow-Origin",author);
//        }
//        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","*");
        response.setHeader("Access-Control-Max-age","3600");
        response.setHeader("Access-Control-Allow-Headers","content-type");
        response.setHeader("Access-Control-Allow-Credentials","true");
        ServletAttributes.setResponse(response);
        return true;
    }


}
